package com.snail.snailvr.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.VRApp;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.snail.snailvr.utils.ChannelUtil;
import com.snail.snailvr.utils.Constant;
import com.snail.snailvr.utils.IntentUtils;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.SharedPreferencesUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.utils.Util;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by lic on 2015/10/21
 * 提示自己更新的dialog
 */
public class UpdateDialogActivity extends Activity implements View.OnClickListener{
    private String downloadUrl;
    private Cursor mCursor;
    private int mIdColumnId;
    public static Intent newIntent(Context context, boolean isNotificationTag, String downloadUrl, String description, int flagActivityNewTask, boolean bFouce) {
        Intent intent = new Intent(context, UpdateDialogActivity.class);
        intent.putExtra(Constant.IS_NOTIFICATION_TAG, isNotificationTag);
        intent.putExtra(Constant.DOWNLOAD_URL, downloadUrl);
        intent.putExtra(Constant.UPDATE_MYSHELF_DESC, description);
        intent.putExtra(Constant.UPDATE_MYSHELF_FORCE, bFouce);
        intent.addFlags(flagActivityNewTask);
        return intent;
    }

    public static final String TAG = UpdateDialogActivity.class.getSimpleName();

    @Bind(R.id.btn_ok)
    TextView btnOK;

    @Bind(R.id.btn_close)
    TextView closeBtn;

    @Bind(R.id.update_content)
    TextView update_content;

    //是否强制更新
    private boolean bFouce = false;

    public void onCreate(Bundle savedInstanceState) {
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        downloadUrl = getIntent().getStringExtra(Constant.DOWNLOAD_URL);
        String desc = getIntent().getStringExtra(Constant.UPDATE_MYSHELF_DESC);
        bFouce = getIntent().getBooleanExtra(Constant.UPDATE_MYSHELF_FORCE, false);

        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_version_control);
        ButterKnife.bind(this);

        update_content.setText(desc);
        btnOK.setOnClickListener(this);
        closeBtn.setOnClickListener(this);

        // 如果强制更新，界面做出相应的变化
        if (bFouce) {
            closeBtn.setVisibility(View.INVISIBLE);
        }
        setFinishOnTouchOutside(false);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_ok:
                if(ChannelUtil.getChannelID().equals(Constant.CHANNEL_GOOGLE_PLAY)){
                    //google play禁止自更新
                    Util.showMarket(UpdateDialogActivity.this);
                }else {
                    long downloadId = SharedPreferencesUtil.getInstance(VRApp.getInstance()).getVersionUpdateDownloadID();
                    if (moveToDownload(downloadId)) {
                        int status = mCursor.getInt(mCursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        LogUtils.d("status===" + (status == DownloadManager.STATUS_RUNNING));
                        if (status == DownloadManager.STATUS_RUNNING) {
                            ToastUtils.showToast(R.string.download_running);
                        } else {
                            startDownload();
                        }
                    } else {
                        LogUtils.d("status=");
                        startDownload();
                    }
                }
                break;
            case R.id.btn_close:

                break;
        }
        finish();
    }

    private void startDownload() {
        DownloadHelper.startDownload(downloadUrl, false, false,0,getString(R.string.app_name));
        IntentUtils.startUpdateService(UpdateDialogActivity.this);
    }

    /**
     * Move {@link #mCursor} to the download with the given ID.
     *
     * @return true if the specified download ID was found; false otherwise
     */
    private boolean moveToDownload(long downloadId) {

        int queryFilter = DownloadManager.STATUS_PENDING
                | DownloadManager.STATUS_RUNNING
                | DownloadManager.STATUS_PAUSED
                | DownloadManager.STATUS_FAILED;

        DownloadManager.Query query = new DownloadManager.Query().setFilterByStatus(queryFilter);

        mCursor = DownloadHelper.getDownloadManager().query(query);
        int count =mCursor.getCount();
        mIdColumnId = mCursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
        for (mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor
                .moveToNext()) {
            if (mCursor.getLong(mIdColumnId) == downloadId) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mCursor!=null)
            mCursor.close();
    }

    @Override
    public void onBackPressed() {
        if (!bFouce) {
            finish();
        }
        else {
        }
    }

}